import UIKit
import BWThemeKit

/// DemoTheme Quick Adaptable
public typealias DemoThemeAdaptableResponder = DemoThemeAdaptable & BWThemeAdaptable
public protocol DemoThemeAdaptable {
    func updateThemeStyleIfNeeded()
}
public extension DemoThemeAdaptable where Self: BWThemeAdaptable {
    func updateThemeStyleIfNeeded() {
        updateThemeIfNeeded(style: DemoTheme.shared.currentStyle as! Self.Style)
    }
}

/// DemoTheme Quickable Extensions
public extension UIColor {
    typealias AppColor = DemoThemeColor
    static func use<T: BWThemeColor>(_ color: T) -> UIColor? {
        return color.themeColor
    }
}

/// DemoTheme Color Quickable
public protocol DemoThemeColorQuickable {
}
public extension BWThemeColor where Self: DemoThemeColorQuickable {
    var themeColor: UIColor? {
        return uiColor(forTheme: DemoTheme.shared.currentStyle as! Self.Style)
    }
    func uiColor(forTheme style: DemoThemeStyle) -> UIColor? {
        return DemoThemeColorStore.shared.getColor(forStyle: style, atScope: Self.self, color: self)
    }
}

/// DemoTheme Notification Name
public extension NSNotification.Name {
    static let DemoThemeStyleDidChange = NSNotification.Name(rawValue: "DemoThemeStyleDidChange")
}

/// DemoTheme User Defaults
public extension UserDefaults {
    static var savedUserThemeStyle: DemoThemeStyle {
        guard
            let saved = standard.value(forKey: "DemoThemeStyle") as? Int,
            let style = DemoThemeStyle(rawValue: saved) else {
            return .unknown
        }
        return style
    }
    static func saveUserThemeStyle(_ style: DemoThemeStyle) {
        standard.setValue(style.rawValue, forKey: "DemoThemeStyle")
        standard.synchronize()
    }
}


/// DemoTheme
public struct DemoTheme: BWTheme {
    public static let shared = DemoTheme()
    
    public var currentStyle: DemoThemeStyle {
        return UserDefaults.savedUserThemeStyle
    }
    public func updateStyle(with newStyle: DemoThemeStyle) {
        guard currentStyle != newStyle else {
            return
        }
        UserDefaults.saveUserThemeStyle(newStyle)
        NotificationCenter.default.post(name: .DemoThemeStyleDidChange, object: nil)
    }
}

/// DemoThemeStyles
public typealias DemoThemeStyle = DemoTheme.Style
public extension DemoTheme {
    enum Style: Int, BWThemeStyle {
        case unknown = -1
        case light
        case dark
    }
}

